<style scoped>
    .spin-icon-load {
        color: #d68146;
        animation: ani-demo-spin 1s linear infinite;
    }
</style>
<template>
    <v-coreLayout ref="coreLayout" :step="0" :countdownTime="120">
        <template slot="content">
            <v-exception ref="exceptionModel"></v-exception>
            <v-preProcessModel ref="preProcessModel"></v-preProcessModel>
            <Row style="height: 100%" type="flex">
                <Col span="24"
                     style="display:flex;justify-content:center;flex-direction:column;padding-left: 90px;padding-right: 90px;">
                    <div style="display:flex;flex-direction:row;align-items: flex-end;">
                        <img src="../images/USB_notice.gif" width="280" style="margin: 5px"/>
                        <Spin style="margin-right: 20px;margin-bottom:10px;" v-if="!scannedQR">
                            <Icon type="ios-loading" size=60 class="spin-icon-load"></Icon>
                        </Spin>
                        <div>
                            <p style="font-size: 32px;color: #d68146">
                                <span v-if="!scannedQR">请插入USB存储设备上传打印文件</span>
                                <span v-else>二维码已扫描，停止监听USB设备</span>
                            </p>
                            <p style="font-size: 22px;">
                                <span v-if="!scannedQR">Please insert USB storage device to upload the print file</span>
                                <span v-else>QR code scanned, stop monitoring USB device</span>
                            </p>
                        </div>
                    </div>

                    <div style="font-size: 18px;margin-top: 30px;color: #808695">
                        <p>
                            <Icon type="ios-alert-outline"/>
                            手机、随身听、录音笔等移动存储设备可能不会被设备正确识别，请将文件转移至U盘重试。
                        </p>
                        <p>
                            <Icon type="ios-alert-outline"/>
                            若您的U盘在一开始就已经插入，请重新插拔设备。
                        </p>
                    </div>

                    <div style="margin: 15px;">
                        <Divider>或</Divider>
                    </div>

                    <div style="display:flex;flex-direction:column;align-items: center;">
                        <Button @click="getQRCodePic()" type="primary" size="large" icon="md-qr-scanner"
                                style="width: 340px;margin-bottom: 10px;height: 50px;">
                            <p style="font-size: 18px;">使用二维码上传文件 / QR Code</p>
                        </Button>
                        <p style="font-size: 18px;color: #2d8cf0">手机文件推荐您通过微信、QQ、支付宝扫描二维码上传</p>
                    </div>

                    <Drawer title="使用二维码上传文件" :closable="true" v-model="qrCodeDrawer" :transfer="false"
                            :inner="true" width="600">
                        <div style="display:flex;flex-direction:column;align-items: center;">

                            <h3>用户唯一编码</h3>
                            <h1 style="color: #d68146">{{this.$root.printUserMark}}</h1>
                            <Divider/>

                            <div ref="uploadQRCode"
                                 style="display: flex;justify-content: center;margin: 20px"></div>
                            <h2>请使用 微信 或 QQ 扫描二维码上传文件</h2>
                            <h3>Please use wechat or QQ to scan QR code to upload files</h3>

                            <Divider/>
                            <p style="font-size: 18px;">
                                根据点墨《用户隐私保护协议》规定，您上传的文件在打印结束后将从服务器永久删除。但若出现违反国家法律法规上传违法、侵权内容，点墨将保留并在公安机关取证提供必要资料，所涉刑事与民事责任由内容提供者自行承担！</p>

                            <Spin fix v-if="scannedQR" style="color: #d68146;font-size: 18px;">
                                <Icon type="ios-loading" size=50 class="spin-icon-load"></Icon>
                                <h3>已扫描二维码<br/>请尽快上传您的文件</h3>
                            </Spin>
                        </div>
                    </Drawer>
                </Col>
            </Row>
        </template>
    </v-coreLayout>
</template>
<script>
    import * as axios from "axios";
    import ExceptionModel from '../components/ExceptionModel.vue';
    import PreProcessModel from '../components/PreProcessModel.vue';
    import CoreLayout from '../components/CoreLayout.vue';
    import QRCode from 'qrcodejs2';

    export default {
        components: {
            'v-exception': ExceptionModel,
            'v-preProcessModel': PreProcessModel,
            'v-coreLayout': CoreLayout,
        },
        data() {
            return {
                qrCodeDrawer: false,
                downloading: true,
                createdQR:false,
                scannedQR: false,

                defeatNum: 0,
                usbListeningSource: {},
            }
        },
        mounted() {
            this.initListenUSBInsertion();
        },
        methods: {
            getQRCodePic() {
                if(!this.createdQR) {
                    this.initWebSocket();
                    new QRCode(this.$refs.uploadQRCode, {
                        text: this.$root.serverUrl + this.$root.userUploadPrintFilePageUrl + "?printUserMark=" + this.$root.printUserMark + "&deviceID=" + this.$root.deviceID,
                        width: 150,
                        height: 150,
                        colorDark: "#333333", //二维码颜色
                        colorLight: "#ffffff", //二维码背景色
                        correctLevel: QRCode.CorrectLevel.L//容错率，L/M/H
                    })
                    this.createdQR=true;
                }
                this.qrCodeDrawer = true;
            },

            initListenUSBInsertion() {
                //[控制端指令]执行端开始监听USB设备接入
                this.usbListeningSource = axios.CancelToken.source();
                console.log(this.usbListeningSource)
                axios({
                    method: 'get',
                    url: 'http://localhost:8999/listenUSBInsertion',
                    cancelToken: this.usbListeningSource.token,
                }).then((response) => {
                    let responseData = response.data;
                    console.log(responseData);
                    if (responseData.state == "SUCCESS") {
                        //USB设备成功接入
                        console.log("USB Device Connection Successful");
                        this.$router.push({
                            name: 'ChooseFile',
                            params: {
                                //转跳并传递参数设备路径参数
                                roots: JSON.parse(responseData.msg),
                            }
                        });
                    }
                }).catch((reason) => {
                    if (reason.message != 'Stop') {
                        this.$refs.exceptionModel.openExceptionModel(this.$root.printUserMark, reason.toString());
                    } else {

                    }
                });
            },
            cancelListenUSBInsertion() {
                this.usbListeningSource.cancel('Stop');
            },
            initWebSocket() { //初始化weosocket
                const url = this.$root.websocketUrl + 'webSocket/' + this.$root.printUserMark;
                this.websock = new WebSocket(url);
                this.websock.onmessage = this.websocketOnMessage;
                this.websock.onopen = this.websocketOnOpen;
                this.websock.onerror = this.websocketOnError;
                this.websock.onclose = this.websocketClose;
            },
            websocketOnOpen() {
                this.$Notice.success({
                    title: '已与服务器建立WEBSOCKET通讯',
                });
            },
            websocketOnError(e) {//连接建立失败重连并返回
                this.defeatNum++;
                console.log("Failure to establish WebSocket connection,The reasons for the error are as follows:");
                console.log(e);
                if (this.defeatNum < 6) {
                    var that = this;
                    if (e.type == "error") {
                        this.$Notice.error({
                            title: '与服务器建立WEBSOCKET通讯失败',
                            desc: '服务器未能响应请求，正在尝试重新连接 (第 ' + this.defeatNum + ' 次 / 共 5 次)，若依然失败，请联系MOTA官方 133-0535-6699 尝试解决此问题！',
                        });
                    }
                    setTimeout(function () {
                        that.initWebSocket()
                    }, 5 * 1000);
                } else {
                    this.$refs.exceptionModel.openExceptionModel(this.$root.printUserMark, "Error: WebSocket连接没有正确建立");
                }
            },
            websocketOnMessage(sendback) {
                var responseData = JSON.parse(sendback.data);
                console.log(responseData);
                if (responseData.state === 'SUCCESS') {
                    if (responseData.code === "1") {
                        //开启扫描二维码成功对话框（LOADING)，防止重复扫码
                        this.scannedQR = true;
                        //关闭USB设备监听，防止用户同时插入USB
                        this.cancelListenUSBInsertion();
                        //重设倒计时
                        this.$refs.coreLayout.countdownReset(300);
                    }
                    if (responseData.code === "2") {
                        this.$Notice.info({
                            title: '文件上传成功',
                            desc: '您上传的文件正在取回自助打印设备',
                            duration: 0,
                            name:'fileDownloadingNotice',
                        });
                        this.downloadFile(responseData);
                    }
                } else {
                    this.$refs.exceptionModel.openExceptionModel(this.$root.printUserMark, responseData.msg, responseData.code, responseData.state);
                }
            },
            websocketSend(data) {//数据发送
                this.websock.send(data)
            },
            websocketClose(e) {  //关闭
                this.websock.close()
                console.log('WebSocket Connection Disconnected', e)
            },
            downloadFile(data) {
                //[控制端指令]执行端通过获得msg内文件名与RandomCode从服务器下载文件
                axios({
                    method: 'get',
                    url: 'http://localhost:8999/download',
                    params: {
                        fileName: data.msg,
                        printUserMark: this.$root.printUserMark,
                    }
                }).then((response) => {
                    let responseData = response.data;
                    if (responseData.state == "SUCCESS") {
                        //解析执行端返回JSON串以获取下载的文件路径与类型
                        let file = JSON.parse(responseData.msg);
                        //关闭下载对话框（MODEL)
                        this.downloading = false;
                        let uploadedFilePath=[];
                        uploadedFilePath.push(file.filePath + file.fileName);
                        let uploadedFileType = file.fileType;
                        this.$Notice.close("fileDownloadingNotice");
                        this.$Notice.success({
                            title: '文件下载成功',
                            desc: '您上传的文件已经取至自助打印设备'
                        });
                        this.$refs.preProcessModel.fileProcessing(this, uploadedFilePath, uploadedFileType);
                    } else {
                        this.$refs.exceptionModel.openExceptionModel(this.$root.printUserMark, responseData.msg, responseData.code, responseData.state);
                    }
                }).catch((reason) => {
                    this.$refs.exceptionModel.openExceptionModel(this.$root.printUserMark, reason.toString());
                });
            }
        }
    }
</script>